<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-9-3
 * Time: 上午10:31
 */
namespace DB;

use Config\Redis;
use Tiny\Logger;

class Token extends MyRedis{
  private $token;
  private $uid;

  public function __construct(string $token = "") {
    parent::__construct(Redis::Redis_host,Redis::Redis_port,Redis::Redis_db,Redis::Redis_password,Redis::Redis_timeout);
    $this->token = $token;
    $this->uid = "";
  }

  /**
   * @param string $uid
   */
  public function initWithUid(string $uid){
    $tokenVal = md5(mt_rand(10,100).$uid.mt_rand(100,1000));
    $this->initWithUidAndToken($tokenVal,$uid);
  }

  /**
   * @param string $tokenVal
   * @param string $uid
   * @throws \Exception
   */
  public function initWithUidAndToken(string $tokenVal,string $uid){
    $this->uid = $uid;
    $this->token = $tokenVal;
    $res = $this->getManager()->get("uid_".$uid);
    if ($res){
      $this->getManager()->del($res);
      $this->getManager()->del("uid_".$uid);
    }
    $result = $this->getManager()->setex($this->token,Redis::Redis_timeout,$this->uid);
    $result = $this->getManager()->set("uid_".$this->uid,$this->token);
    if (!$result){
      Logger::getInstance()->fatal("initWithUidAndToken is error,token is ".$tokenVal.",uid is ".$uid);
      throw new \Exception("initWithUidAndToken error");
    }
  }

  /**
   * @param string $token
   * @return bool
   */
  public function isValid(string $token):bool {
    $manager = $this->getManager();
    $res = $manager->get($token);
    if (!$res){
      return false;
    }
    $this->uid = $res;
    return true;
  }

  public function getUid(){
    return $this->uid;
  }

  public function getToken(){
    return $this->token;
  }
}